package com.bilibili.server.controller;

import com.bilibili.server.dto.Response;
import com.bilibili.server.entity.Category;
import com.bilibili.server.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    // 获取所有启用的分类（公开接口）
    @GetMapping
    public ResponseEntity<Response<List<Category>>> getAllActiveCategories() {
        try {
            List<Category> categories = categoryService.getAllActiveCategories();
            return new ResponseEntity<>(Response.success("获取成功", categories), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 获取单个分类详情（公开接口）
    @GetMapping("/{categoryId}")
    public ResponseEntity<Response<Category>> getCategoryById(@PathVariable int categoryId) {
        try {
            Category category = categoryService.getCategoryById(categoryId);
            if (category == null) {
                return new ResponseEntity<>(Response.error(404, "分类不存在"), HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<>(Response.success("获取成功", category), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 管理员获取所有分类（包括未启用的）
    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Response<List<Category>>> getAllCategories() {
        try {
            List<Category> categories = categoryService.getAllCategories();
            return new ResponseEntity<>(Response.success("获取成功", categories), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 创建新分类（需要admin权限）
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Response<Category>> createCategory(@RequestBody Category category) {
        try {
            Category newCategory = categoryService.createCategory(category);
            return new ResponseEntity<>(Response.created("创建成功", newCategory), HttpStatus.CREATED);
        } catch (RuntimeException e) {
            return new ResponseEntity<>(Response.error(400, e.getMessage()), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 更新分类（需要admin权限）
    @PutMapping("/{categoryId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Response<Category>> updateCategory(@PathVariable int categoryId, @RequestBody Category category) {
        try {
            Category updatedCategory = categoryService.updateCategory(categoryId, category);
            if (updatedCategory == null) {
                return new ResponseEntity<>(Response.error(404, "分类不存在"), HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<>(Response.success("更新成功", updatedCategory), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 删除分类（需要admin权限）
    @DeleteMapping("/{categoryId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Response<Void>> deleteCategory(@PathVariable int categoryId) {
        try {
            categoryService.deleteCategory(categoryId);
            return new ResponseEntity<>(Response.success("删除成功"), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error(500, "服务器内部错误"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}